package com.ztesoft.ossup.report.service;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ztesoft.ossup.report.dao.JdbcTemplateDao;
import com.ztesoft.ossup.report.dao.ReportRepository;
import com.ztesoft.ossup.report.domain.PageData;
import com.ztesoft.ossup.report.domain.Report;

@Service("dataPreviewService")
public class DataPreviewService extends BaseService{

	@Autowired
	JdbcTemplateDao jdbcTemplateDao;
	
	@Autowired
	ReportRepository reportRepository;
	
	public PageData<Map<String, Object>> getDataBySql(String sql,int offset, int limit,int dataRow) {
		Long amount = 0L;
		List<Map<String, Object>> retList = null;
		if (!sql.equals("") && sql != null){
			sql = "select * from ("+ sql + ") ";
			if (dataRow != 0){
				sql = sql + " where rownum <="+dataRow ;
			}
			try{
				amount = jdbcTemplateDao.getDataSize(sql);
				retList = jdbcTemplateDao.getDataByPage(sql, offset, limit);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return new PageData<Map<String, Object>>(amount,retList);
	}
	
	public Report getReportById(Long reportId) {
		Report retReport = null;
		try{
			retReport = reportRepository.findOne(reportId);
		}catch(Exception e){
			e.printStackTrace();
		}
		return retReport;
	} 
	
	public String transforDateForReport(String defaultVal){
		
		DateFormat format=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		if (defaultVal.equals("")){
			return format.format(new Date());
		}
		Calendar cal=Calendar.getInstance();   
		cal.setTime(new Date());   
		int value = Integer.parseInt(defaultVal.substring(0,defaultVal.length()-1));
		if (defaultVal.endsWith("Y")){//Y M H F S
			cal.add(Calendar.YEAR, value);
		}else if(defaultVal.endsWith("M")){
			cal.add(Calendar.MONTH, value);
		}else if(defaultVal.endsWith("D")){
			cal.add(Calendar.DAY_OF_YEAR, value);
		}else if(defaultVal.endsWith("H")){
			cal.add(Calendar.HOUR, value);
		}else if(defaultVal.endsWith("F")){
			cal.add(Calendar.MINUTE, value);
		}else if(defaultVal.endsWith("S")){
			cal.add(Calendar.SECOND, value);
		}
		String dealDate = format.format(cal.getTime());
		return dealDate;
	}
	
}
